package com.waimai.db.dao.impl;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.waimai.db.dao.BaseDao;
import com.waimai.db.dao.UserDao;
import com.waimai.db.entity.ReceiveAddress;
import com.waimai.db.entity.User;

@Repository
@SuppressWarnings("unchecked")
public class UserDaoImpl extends BaseDao implements UserDao {

	public User findUser(User user) {
		String hql = null;
		if (user.getUserId() != null) {
			hql = "FROM User u WHERE u.userId=:userId";
			return (User) getSession().createQuery(hql)
					.setParameter("userId", user.getUserId()).uniqueResult();
		} else if (user.getPassword() == null) {
			hql = "FROM User u WHERE u.phone=:phone";
			return (User) getSession().createQuery(hql)
					.setParameter("phone", user.getPhone()).uniqueResult();
		}

		hql = "FROM User u WHERE (u.userName=:userName OR u.phone=:phone) AND u.password=:password";
		return (User) getSession().createQuery(hql)
				.setParameter("userName", user.getUserName())
				.setParameter("phone", user.getPhone())
				.setParameter("password", user.getPassword()).uniqueResult();
	}

	public User insert(User user) {
		getSession().save(user);
		return user;
	}

	public User update(User user) {
		User userTemp = (User) getSession().get(User.class, user.getUserId());
		if (user != null) {
			if (user.getUserName() != null) {
				userTemp.setUserName(user.getUserName());
			}
			if (user.getPassword() != null) {
				userTemp.setPassword(user.getPassword());
			}
			if (user.getPhone() != null) {
				userTemp.setPhone(user.getPhone());
			}
		}
		return userTemp;
	}

	@SuppressWarnings("unchecked")
	public List<ReceiveAddress> getAddresses(Integer userId) {
		String hql = "FROM ReceiveAddress r WHERE r.user.userId=:userId ORDER BY r.addressId DESC";
		return getSession().createQuery(hql).setParameter("userId", userId)
				.list();
	}

	public List<User> getUsers() {
		// TODO Auto-generated method stub
		String hql = "FROM User u";
		return getSession().createQuery(hql).list();
	}

	public List<Map<String, Object>> getCommentsByUserId(int userId) {
		// TODO Auto-generated method stub
		String hql = "select f.foodName,f.foodPrice,o.orderTime,o.remark,c.content,os.statusName from OrderFood f,Order o,Comment c,OrderStatus os where c.commentId=o.comment.commentId and os.statusId=o.orderstatus.statusId and f.order.orderId=o.orderId and o.user.userId=?";
		return getSession().createQuery(hql).setParameter(0, userId).list();
	}
}
